<template>
  <div class="auth-container">
    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-decoration"></div>
    </div>

    <!-- 注册卡片 -->
    <div class="auth-card">
      <!-- Logo 和标题区域 -->
      <div class="auth-header">
        <div class="logo-section">
          <!-- 小橘 Logo -->
          <div class="logo">
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
              <circle cx="20" cy="20" r="18" fill="var(--orange-primary)" />
              <circle cx="15" cy="16" r="2.5" fill="white" />
              <circle cx="25" cy="16" r="2.5" fill="white" />
              <path d="M13 25 Q20 30 27 25" stroke="white" stroke-width="2" stroke-linecap="round" />
            </svg>
          </div>
          <h1 class="platform-title">创建账号</h1>
        </div>
        <p class="platform-subtitle">加入小橘运维平台</p>
      </div>

      <!-- 注册表单 -->
      <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="auth-form"
        @submit.prevent="handleRegister">
        <!-- 用户名输入框 -->
        <el-form-item prop="username" class="form-item">
          <el-input v-model="registerForm.username" placeholder="用户名" size="large" class="auth-input"
            :prefix-icon="User" clearable />
        </el-form-item>

        <!-- 邮箱输入框 -->
        <el-form-item prop="email" class="form-item">
          <el-input v-model="registerForm.email" type="email" placeholder="邮箱地址" size="large" class="auth-input"
            :prefix-icon="Message" clearable />
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="password" class="form-item">
          <el-input v-model="registerForm.password" type="password" placeholder="密码" size="large" class="auth-input"
            :prefix-icon="Lock" show-password clearable />
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item prop="confirmPassword" class="form-item">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" size="large"
            class="auth-input" :prefix-icon="Lock" show-password clearable />
        </el-form-item>

        <!-- 服务条款 -->
        <div class="form-options">
          <el-checkbox v-model="registerForm.agreeTerms" class="terms-checkbox">
            我已阅读并同意
            <el-link type="primary" :underline="false" class="terms-link">
              服务条款
            </el-link>
            和
            <el-link type="primary" :underline="false" class="terms-link">
              隐私政策
            </el-link>
          </el-checkbox>
        </div>

        <!-- 注册按钮 -->
        <el-form-item class="form-item">
          <el-button type="primary" size="large" class="auth-button" :loading="isLoading"
            :disabled="!registerForm.agreeTerms" @click="handleRegister" native-type="submit">
            {{ isLoading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 登录链接 -->
      <div class="auth-footer">
        <span class="footer-text">已有账号？</span>
        <el-link type="primary" :underline="false" class="login-link" @click="goToLogin">
          立即登录
        </el-link>
      </div>
    </div>

    <!-- 页脚版权信息 -->
    <div class="copyright">
      <p>Powered by WISE-IoT</p>
      <el-link type="info" :underline="false" class="language-switch">
        简体中文 ▼
      </el-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import type { RegisterForm } from './types'

// 路由实例
const router = useRouter()

// 表单引用
const registerFormRef = ref<FormInstance>()

// 响应式数据
const isLoading = ref(false)

// 注册表单数据
const registerForm = reactive<RegisterForm>({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false
})

// 确认密码验证器
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules: FormRules<RegisterForm> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

/**
 * 处理注册提交
 */
const handleRegister = async (): Promise<void> => {
  if (!registerFormRef.value) return

  try {
    // 表单验证
    await registerFormRef.value.validate()

    // 检查服务条款
    if (!registerForm.agreeTerms) {
      ElMessage.warning('请先同意服务条款和隐私政策')
      return
    }

    // 开始加载状态
    isLoading.value = true

    // 模拟注册API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 这里应该调用实际的注册API
    console.log('注册信息:', {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password
    })

    // 注册成功提示
    ElMessage.success('注册成功！请登录您的账号')

    // 跳转到登录页面
    await router.push('/login')

  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    // 结束加载状态
    isLoading.value = false
  }
}

/**
 * 跳转到登录页面
 */
const goToLogin = (): void => {
  router.push('/login')
}
</script>

<style scoped>
/* 使用与登录页面相同的样式 */
@import url('@/assets/styles/auth/auth-styles.css');

/* 注册页面特有样式 */
:deep(.terms-checkbox .el-checkbox__label) {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.terms-link {
  font-size: 13px;
  margin: 0 2px;
}

:deep(.auth-button:disabled) {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
